package com.project.springboot.sseclient;

import com.gitee.yongzhuzl.commonutil.util.id.IdUtil;
import com.gitee.yongzhuzl.commonutil.util.result.ResponseResult;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * 参考：<a href="https://blog.csdn.net/m0_74823963/article/details/145777371">...</a>
 * description: 测试SSE控制器
 * @author 朱正磊
 * @date 2025-10-17 15:09:37
 */
@Controller
@RequestMapping("/api/sse")
public class SseController {

    @Resource
    private SseClient sseClient;

    /**
     * description: 跳转到sse测试页面
     * @author 朱正磊
     * @date 2025-10-17 15:14:06
     * @return 返回逻辑视图地址
     */
    @GetMapping("/toSsePage")
    public String toSseDemo(Model model) {
        String uid = IdUtil.genId16();
        model.addAttribute("uid", uid);
        return "sse/ssePage";
    }

    /**
     * description: 创建sse连接
     * @author 朱正磊
     * @date 2025-10-17 15:17:18
     * @param uid 用户id
     * @return 返回sse发射器
     */
    @GetMapping(value = "/createSse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter createSse(String uid) {
        return sseClient.createSse(uid);
    }

    /**
     * description: 给用户发送消息
     * @author 朱正磊
     * @date 2025-10-17 15:19:53
     * @param uid 用户id
     * @return 返回响应结果
     */
    @GetMapping("/sendMessage")
    @ResponseBody
    public ResponseResult<Void> sendMessage(String uid) {
        for (int i = 0; i < 10; i++) {
            sseClient.sendMessage(uid, "No" + i, "大家好，我是No" + i);
        }
        return ResponseResult.buildSuccess();
    }

    /**
     * description: 断开sse连接
     * @author 朱正磊
     * @date 2025-10-17 15:24:54
     * @param uid 用户id
     * @return 返回响应结果
     */
    @GetMapping("/closeSse")
    @ResponseBody
    public ResponseResult<Void> closeSse(String uid) {
        sseClient.closeSse(uid);
        return ResponseResult.buildSuccess();
    }

}
